package service;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 添加手表验证银行卡
 * @author wangqi
 */
public class AsyncTaskForUpdata extends AsyncTask<String, Void, String> {

	public AsyncTaskForUpdata(Listener listener,Context mcontext) {
		this.listener = listener;
		this.mcontext = mcontext;
		intent= new Intent("ACTION_UPDATE1");
	}
	private Intent intent; 
	private Context mcontext;
	private String downpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/downloads/";
	
	protected String doInBackground(String... urls) {
		String url = urls[0];
		String filename = urls[1];
		return download(url,filename);
	}

	@Override
	protected void onPostExecute(String filepath) {
		try {
			if(!isCancelled()) {
				listener.finish(filepath);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public String download(String url,String filename){
		float filesize,mfinished=0;
		File filepath = new File(downpath);
		if(!filepath.exists()){
			filepath.mkdirs();
		}
		File file = new File(downpath+"/"+filename);
		try {
			file.createNewFile();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			URL durl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) durl.openConnection();
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setInstanceFollowRedirects(true);
			filesize = conn.getContentLength();
			InputStream is=conn.getInputStream();
	        FileOutputStream fs=new FileOutputStream(file);
	        int has=0;
	        byte[] b=new byte[1024];
	        long time = System.currentTimeMillis();
	        while((has=is.read(b))>-1)
	        {
	        	fs.write(b, 0, has);
	        	mfinished = has+mfinished;
	        	
	        	if (System.currentTimeMillis() - time > 100) {
					intent.putExtra("finished", (int)(mfinished*100/ filesize));
					mcontext.sendBroadcast(intent);
					Log.v("jindu",  ((int)(mfinished*100/ filesize))+"");
					time = System.currentTimeMillis();
				}

	        }
	        intent.putExtra("finished", 100);
			mcontext.sendBroadcast(intent);
            is.close();
            fs.close();
            return file.getAbsolutePath();
		} catch (Exception ex) {
			ex.printStackTrace();
			return "";
		}
	}
	
	public interface Listener{
		void finish(String path);
	}
	public Listener listener;

}
